from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from api.models import *
from django.conf import settings
from .common import *
import requests
import json

# Create your views here.
def hello(request):
    """测试接口"""
    return HttpResponse("Hello, I am douyin ' backend!")


def downloadVideo(request):
    """
    返回指定抖音短链接的无水印视频下载地址
    请求参数：抖音短链接地址
    返回结果：抖音无水印视频下载地址
    Host: aweme.snssdk.com
    User-Agent: Aweme/2.7.0 (iPhone; iOS 9.0.1; Scale/2.00)
    """
    try:
        # 处理请求参数
        url = request.GET.get("url", None)
        if url == None:
            raise Exception("The value of the parameter `url` cannot be empty")
        if url == "":
            raise Exception("Please provide parameters `url`")

        # 获取Token       有效期60分钟
        token = getToken()
        # 获取新的设备信息  有效期永久
        device_info = getDevice()

        # aweme_id = getAwemeIdByShortUrl("http://v.douyin.com/dQxxCw/")
        aweme_id = getAwemeIdByShortUrl(url)
        if aweme_id == "":
            raise Exception("ShortUrl parsing error")

        params = {
            "iid": device_info["iid"],
            "idfa": device_info["idfa"],
            "vid": device_info["vid"],
            "device_id": device_info["device_id"],
            "openudid": device_info["openudid"],
            "device_type": device_info["device_type"],
            "os_version": device_info["os_version"],
            "os_api": device_info["os_api"],
            "screen_width": device_info["screen_width"],
            "device_platform": device_info["device_platform"],
            "version_code": APPINFO["version_code"],
            "channel": APPINFO["channel"],
            "app_name": APPINFO["app_name"],
            "build_number": APPINFO["build_number"],
            "app_version": APPINFO["app_version"],
            "aid": APPINFO["aid"],
            "ac": "WIFI",
        }

        postParams = {"aweme_id": aweme_id}

        signParams = params
        signParams.update(postParams)
        sign = getSign(token, signParams)
        params["mas"] = sign["mas"]
        params["as"] = sign["as"]
        params["ts"] = sign["ts"]
        print(params)

        # 获取视频详情
        resp = requests.get(
            "https://aweme.snssdk.com/aweme/v1/aweme/detail/",
            params=params,
            data=postParams,
            headers=header,
        ).json()
        print(resp)
        downloadUrl = resp["aweme_detail"]["video"]["play_addr"]["url_list"][0]
        print("下载地址: " + downloadUrl)

        # saveFile = "douyin.mp4"
        # resp = requests.get(play_addr)
        # open(saveFile, "wb").write(resp.content)
    except Exception as e:
        result = {"success": False, "info": str(e)}
    else:
        result = {"success": True, "downloadUrl": downloadUrl}
    finally:
        return HttpResponse(json.dumps(result))


def userInfo(request):
    """
    获取指定抖音用户的信息
    请求参数：抖音用户uid(用户个人首页获得)
    返回结果：抖音用户个人信息
    Host: aweme.snssdk.com
    User-Agent: Aweme/2.7.0 (iPhone; iOS 9.0.1; Scale/2.00)
    """
    try:
        # 处理请求参数
        shortid = request.GET.get("shortid", None)
        if shortid == None:
            raise Exception("The value of the parameter `shortid` cannot be empty")
        if shortid == "":
            raise Exception("Please provide parameters `shortid`")

        # 获取Token       有效期60分钟
        token = getToken()
        # 获取新的设备信息  有效期永久
        device_info = getDevice()

        # 拼装参数
        params = {
            "iid": device_info["iid"],
            "idfa": device_info["idfa"],
            "vid": device_info["vid"],
            "device_id": device_info["device_id"],
            "openudid": device_info["openudid"],
            "device_type": device_info["device_type"],
            "os_version": device_info["os_version"],
            "os_api": device_info["os_api"],
            "screen_width": device_info["screen_width"],
            "device_platform": device_info["device_platform"],
            "version_code": APPINFO["version_code"],
            "channel": APPINFO["channel"],
            "app_name": APPINFO["app_name"],
            "build_number": APPINFO["build_number"],
            "app_version": APPINFO["app_version"],
            "aid": APPINFO["aid"],
            "ac": "WIFI",
            "count": "12",
            "keyword": shortid,
            "offset": "0",
            # "cursor": 0,
            # "count": 10,
            # "type": 1,
            # "retry_type": "no_retry",
        }
        sign = getSign(token, params)
        params["mas"] = sign["mas"]
        params["as"] = sign["as"]
        params["ts"] = sign["ts"]
        print(params)
        # https://api.amemv.com/aweme/v1/discover/search/?
        # cursor=0&
        # keyword=%s
        # &count=10&
        # type=1&
        # retry_type=no_retry&
        # iid=17900846586&
        # device_id=34692364855&ac=wifi&channel=xiaomi&aid=1128&app_name=aweme&version_code=162&version_name=1.6.2&device_platform=android&ssmix=a&
        # device_type=MI+5&device_brand=Xiaomi&os_api=24&os_version=7.0&uuid=861945034132187&openudid=dc451556fc0eeadb&manifest_version_code=162&
        # resolution=1080*1920&dpi=480&update_version_code=1622' % user_id
        resp = requests.get(
            "https://api.amemv.com/aweme/v1/general/search/",
            params=params,
            headers=header,
        ).json()
        print(resp)

        # 获取uid
        if len(resp["user_list"]) == 0:
            raise Exception("The user was not found")
        uid = resp["user_list"][0]["user_info"]["uid"]

        # 拼装参数
        params = {
            "iid": device_info["iid"],
            "idfa": device_info["idfa"],
            "vid": device_info["vid"],
            "device_id": device_info["device_id"],
            "openudid": device_info["openudid"],
            "device_type": device_info["device_type"],
            "os_version": device_info["os_version"],
            "os_api": device_info["os_api"],
            "screen_width": device_info["screen_width"],
            "device_platform": device_info["device_platform"],
            "version_code": APPINFO["version_code"],
            "channel": APPINFO["channel"],
            "app_name": APPINFO["app_name"],
            "build_number": APPINFO["build_number"],
            "app_version": APPINFO["app_version"],
            "aid": APPINFO["aid"],
            "ac": "WIFI",
            "user_id": uid,  # 用户userid
        }

        sign = getSign(token, params)
        params["mas"] = sign["mas"]
        params["as"] = sign["as"]
        params["ts"] = sign["ts"]
        print(params)

        # 拉取用户个人信息
        resp = requests.get(
            "https://aweme.snssdk.com/aweme/v1/user/", params=params, headers=header
        ).json()
        print(json.dumps(resp))

        print("uid: ", resp["user"]["uid"])
        print("city: ", resp["user"]["city"])
        print("nickname: ", resp["user"]["nickname"])
        print("total_favorited: ", resp["user"]["total_favorited"])
        print("following_count: ", resp["user"]["following_count"])
        print("follower_count: ", resp["user"]["follower_count"])

    except Exception as e:
        result = {"success": False, "info": str(e)}
    else:
        result = {"success": True, "data": resp}
    finally:
        return HttpResponse(json.dumps(result))


def downloadAllVideos(request):
    """
    批量下载指定用户的所有作品
    请求参数：抖音用户uid(就是抖音号，用户个人首页获得)
    返回结果：该抖音用户所有的作品下载链接
    Host: aweme.snssdk.com
    User-Agent: Aweme/2.7.0 (iPhone; iOS 9.0.1; Scale/2.00)
    """
    try:
        # 处理请求参数
        shortid = request.GET.get("shortid", None)
        if shortid == None:
            raise Exception("The value of the parameter `shortid` cannot be empty")
        if shortid == "":
            raise Exception("Please provide parameters `shortid`")
        print('Start downloadAllVideos...')

        # 获取Token       有效期60分钟
        token = getToken()
        # 获取新的设备信息  有效期永久
        device_info = getDevice()

        # 拼装参数
        params = {
            "iid": device_info["iid"],
            "idfa": device_info["idfa"],
            "vid": device_info["vid"],
            "device_id": device_info["device_id"],
            "openudid": device_info["openudid"],
            "device_type": device_info["device_type"],
            "os_version": device_info["os_version"],
            "os_api": device_info["os_api"],
            "screen_width": device_info["screen_width"],
            "device_platform": device_info["device_platform"],
            "version_code": APPINFO["version_code"],
            "channel": APPINFO["channel"],
            "app_name": APPINFO["app_name"],
            "build_number": APPINFO["build_number"],
            "app_version": APPINFO["app_version"],
            "aid": APPINFO["aid"],
            "ac": "WIFI",
            "count": "12",
            "keyword": shortid,
            "offset": "0",
            # "cursor": 0,
            # "count": 10,
            # "type": 1,
            # "retry_type": "no_retry",
        }
        sign = getSign(token, params)
        params["mas"] = sign["mas"]
        params["as"] = sign["as"]
        params["ts"] = sign["ts"]
        print(params)

        resp = requests.get(
            "https://api.amemv.com/aweme/v1/general/search/",
            params=params,
            headers=header,
        ).json()
        print(resp)

        # 获取uid
        if len(resp["user_list"]) == 0:
            raise Exception("The user was not found")
        uid = resp["user_list"][0]["user_info"]["uid"]

        # 拼装参数
        params = {
            "iid": device_info["iid"],
            "idfa": device_info["idfa"],
            "vid": device_info["vid"],
            "device_id": device_info["device_id"],
            "openudid": device_info["openudid"],
            "device_type": device_info["device_type"],
            "os_version": device_info["os_version"],
            "os_api": device_info["os_api"],
            "screen_width": device_info["screen_width"],
            "device_platform": device_info["device_platform"],
            "version_code": APPINFO["version_code"],
            "channel": APPINFO["channel"],
            "app_name": APPINFO["app_name"],
            "build_number": APPINFO["build_number"],
            "app_version": APPINFO["app_version"],
            "aid": APPINFO["aid"],
            "ac": "WIFI",
            "user_id": uid,  # 用户userid
        }

        sign = getSign(token, params)
        params["mas"] = sign["mas"]
        params["as"] = sign["as"]
        params["ts"] = sign["ts"]
        print(params)

        # 获取用户的所有作品信息
        resp = requests.get(
            "https://aweme.snssdk.com/aweme/v1/aweme/post/",
            params=params,
            headers=header,
        ).json()
        print(json.dumps(resp))

    except Exception as e:
        result = {"success": False, "info": str(e)}
    else:
        result = {"success": True, "data": resp}
    finally:
        return HttpResponse(json.dumps(result))



